#include "stdafx.h"
#include "category_xml.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ReadCategoryXml(const char *p_path, const int catagoryStyle, const int categoryIndex, char *p_categoryName) {
	char *p_buffer = NULL;
	char *p_find = NULL;
	char *p_findTitle = NULL;
	char *p_findIndex = NULL;
	char *p_findName = NULL;
	char *p_findEnd = NULL;
	char chIndex[16] = {0};
	char chName[64] = {0};
	int buf_size;

	FILE *pf = fopen(p_path, "rb");
	if (NULL == pf) {
		return -1;
	}
	else {
		fseek(pf, 0, SEEK_END);
		buf_size = ftell(pf);
		fseek(pf, 0, SEEK_SET);
		p_buffer = (char *)malloc(buf_size + 1);
		ASSERT(NULL != p_buffer);
		fread(p_buffer, sizeof(char), buf_size, pf);
		switch (catagoryStyle) {
			case CATEGORY_VIOTYPE:
				p_find = strstr(p_buffer, "\"violation\"");
				break;
			case CATEGORY_CARCOLOR:
				p_find = strstr(p_buffer, "\"vehicle_color\"");
				break;
			case CATEGORY_CARTYPE:
				p_find = strstr(p_buffer, "\"vehicle\"");
				break;
			case CATEGORY_LOGO:
				p_find = strstr(p_buffer, "\"car_brand\"");
				break;
			case CATEGORY_CHEXI:
				p_find = strstr(p_buffer, "\"car_chexi\"");
				break;
			case CATEGORY_CHEXING:
				p_find = strstr(p_buffer, "\"car_chexing\"");
				break;
			default:
				p_find = NULL;
				break;
		}
		if (NULL != p_find) {
			sprintf(chIndex, "\"%d\"", categoryIndex);
			p_findTitle = strstr(p_find, "</category>");
			p_findIndex = strstr(p_find, chIndex);
			if (0 < (p_findTitle - p_findIndex)) {
				if (NULL != p_findIndex) {
					p_findName = strstr(p_findIndex, "name");
					p_findEnd = strstr(p_findName + 6, "\"");
					strncpy(chName, p_findName + 6, p_findEnd - p_findName - 6);
					chName[p_findEnd - p_findName - 6] = 0;
				}
			}
		}
		free(p_buffer);
		fclose(pf);
		if (0 == strcmp(chName, "")) {
			strcpy(p_categoryName, "");
			return -11;
		}
		else {
			strcpy(p_categoryName, chName);
			return 1;
		}
	}
}


#if 0
int main(void) {
	char name[64];
	int xml_ret;

	xml_ret = ReadCategoryXml("categories.xml", CATEGORY_CARTYPE, 0, name);
	return 0;
}
#endif
